<template>
	<view class="content">
		<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" plain="true">
			<image class="avatar" :src="user.image ? (baseUrl + user.image) : defaultUserAvatar"></image>
			<view class="avatar-text">
				<u-icon name="camera" color="rgba(255,255,255,.8)" size="26"></u-icon>
			</view>
		</button>
		<view class="tips">
			点击更换头像
		</view>
		
		<u-cell title="昵称" isLink>
			<u--input placeholder="请输入昵称" inputAlign="right" slot="value" border="none" type="nickname" v-model="user.name" @blur="updateNickname"></u--input>
		</u-cell>
		<u-cell title="手机号" isLink >
			<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" slot="value" class="btn_phone" >{{user.mobile || '未绑定'}}</button>
		</u-cell>

	</view>
</template>

<script>
	import {
		userinfo,edituserinfo,avatar,setphone
	} from '@/api/user'
	import {baseUrl} from '@/api/request.js'
	export default {
		data() {
			return {
				baseUrl,
				user:{},
				defaultUserAvatar:require('@/static/images/default_user.png')
			}
		},
		onLoad() {
			this.getUserInfo()
		},
		methods: {
			onChooseAvatar(e) {
				const { avatarUrl } = e.detail
				avatar(avatarUrl).then(res=>{
					uni.showToast({
						title:'头像修改成功',icon:'none'
					})
					this.getUserInfo()
				})
			},
			getUserInfo(){
				userinfo().then(res=>{
					uni.setStorageSync("user", res.data)
					this.user = res.data
				})
			},
			updateNickname(value){
				console.log(value);
				edituserinfo({nickname:value}).then(res=>{
					uni.showToast({
						title:'昵称修改成功',icon:'none'
					})
					this.getUserInfo()
				})
			},
			// 获取用户手机号
			getPhoneNumber(e){
				console.log(e.detail)                           // 判断用户是否允许获取手机号
				if(e.detail.errMsg == "getPhoneNumber:ok"){     // 用户允许或去手机号
					setphone({code:e.detail.code}).then(res=>{
						this.getUserInfo()
						userinfo().then(res=>{
							uni.setStorageSync("user", res.data)
						})
					})
				}else {
					uni.showToast({
						title:'拒绝授权手机号',icon:'none'
					})
				}
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}
	.content {
		.tips {
			text-align: center;
			font-size: 28rpx;
			font-weight: 500;
			color: #999999;
			line-height: 84rpx;
		}
	}
	.avatar-wrapper {
		padding: 0;
		width: 160rpx !important;
		border-radius: 50%;
		margin-top: 80rpx;
		border: 0 !important;
		.avatar {
			display: block;
			width: 160rpx;
			height: 160rpx;
		}
		.avatar-text {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 160rpx;
			height: 160rpx;
			font-size: 20rpx;
			background: rgba(0,0,0,0.5);
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	.btn_phone {
		background-color: transparent;
		height: auto;
		padding: 0;
		margin: 0;
		height: 48rpx;
		line-height: 1.5;
		font-size: 30rpx;
		width: 50%;
		text-align: right;
	}
	.btn_phone::after{
		border: none;
	}
	
</style>
